package com.huang.foundation.config;

import com.huang.foundation.constant.FoundationConstants;
import com.huang.utils.RedisUtil;
import com.huang.utils.entity.enums.RedisKeyPrefixes;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import toolgood.words.StringSearch;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author HuangShen
 * @Date 2022/3/2 07:11
 * @Describe
 */
@Configuration
public class SensitiveWordsConfig {
    @Resource(name = "myRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate;

    @Bean(name = "stringSearch")
    public StringSearch buildStringSearch() {
        StringSearch stringSearch = new StringSearch();
        // 从redis中获取 词库构建索引
        String key = RedisUtil.createKey(RedisKeyPrefixes.SensitiveWordsList, "VALUE");
        Long size = redisTemplate.opsForList().size(key);
        List<String> keywords = (List<String>)(List) redisTemplate.opsForList().range(key, 0, size);
        stringSearch.SetKeywords(keywords);
        return stringSearch;
    }

    @Autowired
    public void flushSensitiveWords(StringSearch stringSearch){
        String flushKey = RedisUtil.createKey(RedisKeyPrefixes.SensitiveWordsList, "ISFLUSH");
        String isFlush =(String) redisTemplate.opsForValue().get(flushKey);
        if (StringUtils.equals(isFlush,FoundationConstants.FLUSH_SENSITIVE_WORDS)){
            // 从redis中获取 词库构建索引
            String key = RedisUtil.createKey(RedisKeyPrefixes.SensitiveWordsList, "VALUE");
            Long size = redisTemplate.opsForList().size(key);
            List<String> keywords = (List<String>)(List) redisTemplate.opsForList().range(key, 0, size);
            stringSearch.SetKeywords(keywords);
            redisTemplate.opsForValue().set(flushKey, FoundationConstants.NO_FLUSH_SENSITIVE_WORDS);
        }
    }




}
